package com.ljx.demo.utils;

import com.ljx.demo.domain.entity.User;
import com.ljx.demo.security.core.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-06-16  23:41
 */
public class JwtUtil {

    private final static String SECRET = "a!@#hdqB_+_)1+*@!";
    private final static long MILLIS_MINUTE_TEN = 20 * 60 * 1000L; // 过期时间20分钟

    public static String createToken(String username){
        Map<String, Object> data = new HashMap<>();
        data.put("uuid", "1231231231"); // 这里需要用随机数创创建

        return Jwts.builder().setClaims(data)
                .signWith(SignatureAlgorithm.HS512, SECRET).compact();
    }


    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    public static String getToken(HttpServletRequest request){
        String token = request.getHeader("token");
        // 获取真实Token
        // 若Token中存在前缀需要去掉
        // 若Redis中存在的Token有UUID等参数也需要加上
        String trueToken = token;

        return trueToken;
    }

    public static LoginUser getLoginUser(HttpServletRequest request){
        // 获取请求携带的令牌
        String token = getToken(request);
        if (Objects.nonNull(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String userKey = "login_uuid:" + claims.get("uuid");
                // 根据userKey从Redis中获取
                // ...，这里模拟返回的数据
                return new LoginUser(new User("123", "12312"), getPermsList(), System.currentTimeMillis());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static Set<String> getPermsList() {
        Set<String> res = new HashSet<>();
        res.add("user:t1");
        res.add("user:t2");

        return res;
    }

    public static void verifyRefreshToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            // 刷新Redis中的token过期时间
            // ...
        }
    }
}
